<template>
  <div class="member-list">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="用户">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="searchForm.level" placeholder="请选择会员等级" clearable>
            <el-option label="普通会员" value="basic" />
            <el-option label="黄金会员" value="gold" />
            <el-option label="钻石会员" value="diamond" />
            <el-option label="VIP会员" value="vip" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>会员列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="memberList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="会员ID" width="80" />
        <el-table-column prop="username" label="用户" />
        <el-table-column prop="level" label="会员等级" width="100">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.level)">
              {{ getLevelText(scope.row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expiryDate" label="到期时间" width="180" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 会员编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="memberFormRef"
        :model="memberForm"
        :rules="memberFormRules"
        label-width="100px"
      >
        <el-form-item label="用户" prop="username">
          <el-input v-model="memberForm.username" disabled />
        </el-form-item>
        <el-form-item label="会员等级" prop="level">
          <el-select v-model="memberForm.level" placeholder="请选择会员等级">
            <el-option label="普通会员" value="basic" />
            <el-option label="黄金会员" value="gold" />
            <el-option label="钻石会员" value="diamond" />
            <el-option label="VIP会员" value="vip" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期时间" prop="expiryDate">
          <el-date-picker
            v-model="memberForm.expiryDate"
            type="date"
            placeholder="请选择到期时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveMember" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useMemberStore } from '@/stores'

// 使用会员store
const memberStore = useMemberStore()

// 搜索表单
const searchForm = reactive({
  username: '',
  level: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => memberStore.total)
})

// 会员列表（从store中获取）
const memberList = computed(() => memberStore.memberList)
const loading = computed(() => memberStore.loading)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const memberFormRef = ref()

// 会员表单
const memberForm = reactive({
  id: null,
  userId: null,
  username: '',
  level: '',
  expiryDate: ''
})

// 会员表单验证规则
const memberFormRules = {
  level: [
    { required: true, message: '请选择会员等级', trigger: 'change' }
  ],
  expiryDate: [
    { required: true, message: '请选择到期时间', trigger: 'change' }
  ]
}

// 获取会员等级标签类型
const getLevelTagType = (level) => {
  switch (level) {
    case 'basic':
      return 'info'
    case 'gold':
      return 'warning'
    case 'diamond':
      return 'primary'
    case 'vip':
      return 'success'
    default:
      return 'info'
  }
}

// 获取会员等级文本
const getLevelText = (level) => {
  switch (level) {
    case 'basic':
      return '普通会员'
    case 'gold':
      return '黄金会员'
    case 'diamond':
      return '钻石会员'
    case 'vip':
      return 'VIP会员'
    default:
      return '未知'
  }
}

// 获取会员列表
const fetchMemberList = async () => {
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    username: searchForm.username,
    level: searchForm.level,
    dateRange: searchForm.dateRange
  }
  
  try {
    await memberStore.fetchMemberList(params)
  } catch (error) {
    ElMessage.error('获取会员列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchMemberList()
}

// 处理重置
const handleReset = () => {
  searchForm.username = ''
  searchForm.level = ''
  searchForm.dateRange = []
  pagination.currentPage = 1
  fetchMemberList()
}

// 处理导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 处理查看会员
const handleView = (row) => {
  dialogTitle.value = '查看会员'
  isEdit.value = false
  dialogVisible.value = true
  
  // 填充表单数据
  Object.assign(memberForm, row)
}

// 处理编辑会员
const handleEdit = (row) => {
  dialogTitle.value = '编辑会员'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  Object.assign(memberForm, row)
}

// 处理保存会员
const handleSaveMember = () => {
  if (!memberFormRef.value) return
  
  memberFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        if (isEdit.value) {
          await memberStore.updateMember(memberForm.id, memberForm)
          ElMessage.success('更新成功')
        } else {
          await memberStore.createMember(memberForm)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        await fetchMemberList()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 处理对话框关闭
const handleDialogClose = () => {
  if (memberFormRef.value) {
    memberFormRef.value.resetFields()
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchMemberList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchMemberList()
}

// 组件挂载后获取会员列表
onMounted(() => {
  fetchMemberList()
})
</script>

<style lang="scss" scoped>
.member-list {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>